/****
	Copyright 2011 Taras Kulbachka

	Licensed under the Apache License, Version 2.0 (the "License");
	you may not use this file except in compliance with the License.
	You may obtain a copy of the License at

		http://www.apache.org/licenses/LICENSE-2.0

	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License.
*/
package com.atdevsoft.apps.abyss;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.PowerManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;

import org.htmlparser.filters.NodeClassFilter;
import org.htmlparser.nodes.TagNode;
import org.htmlparser.util.NodeList;

import com.atdevsoft.apps.abyss.AbstractQuoteDownloader.OnPageProcessedListener;


public class DownloadActivity extends Activity {
	private static final int DEFAULT_PAGES_COUNT = 3;
	private static final String LOCK_NAME_STATIC = "com.atdevsoft.apps.abyss";
	private static PowerManager.WakeLock lockStatic = null;	
	
	private class BashQuoteDownloader extends AbstractQuoteDownloader {
		private static final String BASE_ADDRESS = "http://bash.org.ru/abyssbest";
		
		private static final int SKIP_BEFORE_DIE = 3;
		private static final int GAP_TO_FALLBACK = 10;				
		
		private int mLastDlQuote;
		private int mTargetNodeOnPage;	
		private NodeClassFilter mNodeFilter;
		
		public BashQuoteDownloader(SQLiteDatabase db, String tableName) {
			super(db, tableName);
		}
		
	    private boolean checkIfNumber(String in) {        
	        try {
	            Integer.parseInt(in);        
	        } catch (NumberFormatException ex) {
	            return false;
	        }        
	        return true;
	    }	
	    
	    @Override
	    protected int getNearestSavedQuote(int quoteId) {
			int res = 0;
	        Cursor getQuote = mDb.rawQuery("select " + DatabaseHelper.QUOTES_SOURCE_ID + 
	        		" from " + DatabaseHelper.TABLE_NAME_ABYSSBESTQUOTES + 
	        		" where " +	DatabaseHelper.QUOTES_SOURCE_ID + " >= " + String.valueOf(quoteId) +
	        		" order by 1 asc limit 0, 1", null);
	        if (getQuote.getCount() == 1) {
	        	getQuote.moveToFirst();
	        	res = getQuote.getInt(0);
	        }
	        getQuote.close();
	        return res;			
		}				

	    @Override
		protected String getPageAddress(int pageNumber) {
			if (pageNumber <= 0)
				return BASE_ADDRESS;
			else
				return BASE_ADDRESS + "/" + String.valueOf(pageNumber);
		}
		
		@Override
		protected boolean processTag(TagNode tag, ContentValues output, boolean fastDownload) {
            String txt;
            
            if (("input".equals(tag.getRawTagName())) && ("page".equals(tag.getAttribute("name"))) && 
            		("page".equals(tag.getAttribute("class")))) {
            	txt = tag.getAttribute("value");
            	if ((txt != null) && checkIfNumber(txt))
            		QuotesSitePageNumber = Integer.parseInt(txt);
            	return false;		
       		}
       		
            if ("quote".equals(tag.getAttribute("class"))) {
            	mTargetNodeOnPage++;          
            	            	
            	NodeList children = tag.getChildren().extractAllNodesThatMatch(mNodeFilter); 
            	// children.size() == 2 -- otherwise it is ad block
            	// mTargetNodeOnPage > 1 -- first target node on bash is search box
            	if ((children.size() == 2) && (children.elementAt(0).getChildren().size() > 4) && (mTargetNodeOnPage > 1)) {  
            		NodeList headerNodes = children.elementAt(0).getChildren();
            		mLastDlQuote = Integer.parseInt(headerNodes.elementAt(3).getChildren().elementAt(0).getText().trim().substring(4));
            		
            		int nearestQuote = 0;
            		if (!fastDownload)
            			nearestQuote = getNearestSavedQuote(mLastDlQuote);
            		
            		if (nearestQuote == mLastDlQuote) {
            			if ((mTerminateOnDuplicates) && (PageSkippedQuotes >= SKIP_BEFORE_DIE)) { 
            				Status = STATUS_ABORT;
            			} else {
            				Status = STATUS_SKIP_QUOTE;            			
            			}
            		} else if (nearestQuote == 0 || (nearestQuote - mLastDlQuote < GAP_TO_FALLBACK)) {
            			output.put(DatabaseHelper.QUOTES_SOURCE_ID, mLastDlQuote); // quote source id
            			output.put(DatabaseHelper.QUOTES_POSTED, headerNodes.elementAt(1).getChildren().elementAt(0).getText().trim()); // quote posted at            		
            			output.put(DatabaseHelper.QUOTES_QUOTE, children.elementAt(1).toHtml()); // quote text	            		
            			Status = STATUS_OK;
            		} else {
            			Status = STATUS_FALLBACK_PAGE;
            			
            		}	            		
            	}
            	
            	return false;
            }
           	return true;			
		}

		@Override
		public void parsePage(String page, boolean terminateOnDuplicates, boolean fastDownload) {            
			mTargetNodeOnPage = 0;
			mNodeFilter = new NodeClassFilter(TagNode.class);
			super.parsePage(page, terminateOnDuplicates, fastDownload);
		}
	}
	
	private Button mBtnStart;
	private Button mBtnCancel;	
	private EditText mEtPagesCount;
	private ProgressBar mPbProgress;
	private TextView mTvProgress;	
	private CheckBox mCbStopOnDup;	
	private CheckBox mCbFastDownload;		

	
	private Context mContext;	
	
	private int mPagesCount;
	
	
	private class Updater extends Thread {
		@Override
		public void run() {
	        SQLiteDatabase db = new DatabaseHelper(mContext).getWritableDatabase();
	        BashQuoteDownloader bqd = new BashQuoteDownloader(db, DatabaseHelper.TABLE_NAME_ABYSSBESTQUOTES);
        
	        bqd.setOnPageProcessedListener(new OnPageProcessedListener() {
				@Override
				public void onPageProcessed(final int page, final int quotesAdded, final int quotesSkipped) {
					runOnUiThread(new Runnable() {						
						@Override
						public void run() {
					        mPbProgress.setProgress(mPbProgress.getProgress() + 1);
					        mTvProgress.setText(String.format(mContext.getString(R.string.download_progress_data), page, quotesAdded, quotesSkipped));
						}
					});
				}
				
				@Override
				public void onAllPagesProcessed(final int resultCode, final int totalQuotesAdded) {
					runOnUiThread(new Runnable() {												
						@Override
						public void run() {
							lockStatic.release();
					        if (totalQuotesAdded > 0) {
								Toast t = Toast.makeText(mContext, String.format(mContext.getString(R.string.download_finished), totalQuotesAdded), Toast.LENGTH_LONG);
						        t.show();
					        	setResult(RESULT_OK);
					        	finish();
					        } else {
								Toast t = Toast.makeText(mContext, mContext.getString(R.string.no_quotes), Toast.LENGTH_LONG);
						        t.show();					        	
					        }
							mBtnStart.setEnabled(true);
						}
					});
				}
			});

	        PowerManager mgr = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);			
	        lockStatic = mgr.newWakeLock(PowerManager.FULL_WAKE_LOCK, LOCK_NAME_STATIC); 	        
	        lockStatic.acquire();
	        bqd.parsePages(mPagesCount, mCbStopOnDup.isChecked(), mCbFastDownload.isChecked(), true);	        
	        db.close();	       
		}
	}	 	
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ac_download);

        LayoutParams params = getWindow().getAttributes(); 
        params.width = LayoutParams.FILL_PARENT; 
        getWindow().setAttributes((android.view.WindowManager.LayoutParams) params);        
        
        mContext = this;
        mBtnStart = (Button)findViewById(R.id.btn_ok);
        mBtnCancel = (Button)findViewById(R.id.btn_cancel);      
        mPbProgress = (ProgressBar)findViewById(R.id.pb_progress);
        mEtPagesCount = (EditText)findViewById(R.id.et_pages_count);
        mTvProgress = (TextView)findViewById(R.id.tv_progress);
        mCbStopOnDup = (CheckBox)findViewById(R.id.cb_stop_on_dup);
        mCbFastDownload = (CheckBox)findViewById(R.id.cb_fast_download);        

        
        mBtnCancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();				
			}
		});
        
        mBtnStart.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {				
				mBtnStart.setEnabled(false);
		        try {
		        	mPagesCount = Integer.parseInt(mEtPagesCount.getText().toString());
		        } catch (NumberFormatException e) {
		        	mPagesCount = DEFAULT_PAGES_COUNT;
		        }
		        mPbProgress.setMax(mPagesCount);
		        mPbProgress.setProgress(0);
		        
		        Updater up = new Updater();
		        up.start();				
			}
		});       
        
        mCbFastDownload.setOnCheckedChangeListener(new OnCheckedChangeListener() {			
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				mCbStopOnDup.setEnabled(!isChecked);				
			}
		});
    }
    
}